package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import common.RowMapper;
import common.SQLTemplate;

import pojo.CustomerType;
import dao.CustomerTypeDAO;

public class CustomerTypeDAOImpl extends BaseDAO implements CustomerTypeDAO {

	@Override
	public List<CustomerType> getCustomerTypes() {
		String sql = SQLTemplate.CUSTOMER_TYPE_SELECT_TEMPLATE + ";";
		List<CustomerType> customerTypes = null;
		try {
			customerTypes = (List<CustomerType>) queryForList(sql,
					new CustomerTypeRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return customerTypes;
	}

	@Override
	public CustomerType add(CustomerType customerType) {
		String tableName = "T_CUSTOMER_TYPE";
		String[] columnNames = { "TYPE" };
		String[] values = { customerType.getType() };
		String sql = SQLTemplate.addSQLTemplate(tableName, columnNames, values);
		try {
			insert(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return customerType;
	}

	@Override
	public CustomerType update(CustomerType customerType) {
		String tableName = "T_CUSTOMER_TYPE";
		String[] columnNames = { "TYPE" };
		String[] values = { customerType.getType() };
		String sql = SQLTemplate.updateSQLTemplate(tableName, columnNames,
				values) + "WHERE ID='" + customerType.getId() + "';";
		try {
			update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return customerType;
	}

	@Override
	public boolean deleteById(String id) {
		boolean state = false;
		String sql = SQLTemplate.deleteSQLTemplate("T_CUSTOMER_TYPE")
				+ "WHERE ID='" + id + "';";
		try {
			delete(sql);
			state = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return state;
	}

	private class CustomerTypeRowMapper implements RowMapper<Object> {
		private CustomerTypeRowMapper() {
		}

		public CustomerType mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			String id = rs.getString("id");
			String type = rs.getString("type");
			CustomerType customerType = new CustomerType();
			if (id != null) {
				customerType.setId(id);
			}
			if (type != null) {
				customerType.setType(type);
			}
			return customerType;
		}
	}

}
